package zpx.web;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.compass.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import zpx.iservice.IComAttachmentService;
import zpx.iservice.IMaterialService;
import zpx.model.ComAttachment;
import zpx.model.DataDictionaryItem;
import zpx.model.Material;
import zpx.model.User;
import zpx.util.XMLDDItemParser;

@SuppressWarnings("restriction")
@Controller
@RequestMapping("/material")
public class MaterialController {
	
	private IMaterialService materialService;

	public IMaterialService getMaterialService() {
		return materialService;
	}
	
	@Resource
	public void setMaterialService(IMaterialService materialService) {
		this.materialService = materialService;
	}
	
	@Autowired
	private IComAttachmentService comAttachmentService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/goMaterialList")
	//@RequestMapping(value={"/goMaterialList","/"},method=RequestMethod.GET)
	public ModelAndView goMaterialList() {
		Map<String, Object> map = new HashMap<String, Object>();
    	List<DataDictionaryItem> materialStatus=XMLDDItemParser.getDataDictionaryItems("MaterialStatus").getDataDictioanryItems();
    	
    	JSONArray jsonArray = JSONArray.fromObject(materialStatus);
    	map.put("materialStatus",jsonArray);
		return new ModelAndView("material/materialList",map);
	}
	
	/**
	 * 获得物料列表数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/getMaterialList",method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public JSONObject getMaterialList(HttpServletRequest request, HttpServletResponse response) {
		// 查询条件
        Map<String, String> searchMap = new HashMap<String, String>();
		JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        // 获取页面显示的总数量
        int total = this.materialService.getMaterialCount(searchMap);
        // 取得的开始记录数
        int startIndex = 0;
        // 每页取得的数量
        int pageSize = 20;
        String rows = request.getParameter("rows");
        String page = request.getParameter("page");
        // 计算分页显示
        if (rows != null && !"".equals(rows) && page != null && !"".equals(page)) {
            int iPage = Integer.parseInt(page);
            pageSize = Integer.parseInt(rows);
            startIndex = (iPage - 1) * pageSize;
            while (startIndex >= total && startIndex > 0) {
                iPage--;
                startIndex = (iPage - 1) * pageSize;
            }
            searchMap.put("startIndex", startIndex + "");
            searchMap.put("pageSize", pageSize + "");
        }
        List<Material> datalist=materialService.getMaterialsList(searchMap);
        // 为空时
        if (datalist == null) {
            datalist = new ArrayList<Material>();
        }
        // 正常返回
        if (datalist != null) {
            for (Material material : datalist) {
                jsonArray.add(this.getMaterialToJsonObj(material));
            }
        }
        jsonObject.put("rows", jsonArray);
        jsonObject.put("total", total);
		return jsonObject;
	}
	/**
	 * 跳转到物料添或编辑页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("materialAddOrEdit")
	public ModelAndView materialAddOrEdit(HttpServletRequest request,
            HttpServletResponse response){
		String operWay=request.getParameter("operWay");
    	
    	Map<String, Object> map = new HashMap<String, Object>();
    	String id=request.getParameter("id");
    	Material material=new Material();
    	// 编辑
    	if(operWay.equals("2")){
    		
    		material=materialService.getMaterial(id);
    	}
    	// 附件列表
        List<ComAttachment> attaList = new ArrayList<ComAttachment>();
        if (id != null && !"".equals(id)) {
            // 附件列表
            attaList = comAttachmentService.getAttachments(id);
        }
    	
    	map.put("material", material);
    	map.put("comAttachments", attaList);
        return new ModelAndView("material/materialAddorEdit",map);
	}
	
	
    /**
     * 
     * 保存物料信息
     * @param request
     * @param response
     * @return
     */
	@RequestMapping(value="/saveMaterial",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> saveMaterial(HttpServletRequest request, Material material,String fileNames,String filePaths,String delComAttIds) {
		User loginUser = (User)request.getSession().getAttribute("loginUser");
		Map<String, Object> searchMap=new HashMap<String, Object>();
		searchMap.put("material", material);
		searchMap.put("fileNames", fileNames);
		searchMap.put("filePaths", filePaths);
		searchMap.put("delComAttIds", delComAttIds);
		searchMap.put("loginUser", loginUser);
		materialService.saveOrUpdate(searchMap);
		Map<String, String> returnMap = new HashMap<String, String>();
        returnMap.put("info", "success");
		return returnMap;
	}
	
	private JSONObject getMaterialToJsonObj(Material material){
		JSONObject jsonObj = new JSONObject();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if(material.getId()!=null){
            jsonObj.put("id",material.getId());
        }
        if(material.getCreateDate()!=null){
            jsonObj.put("createDate",dateFormat.format(material.getCreateDate()));
        }
        if(StringUtils.hasText(material.getCreatePerson())){
            jsonObj.put("createPerson",material.getCreatePerson());
        }
        if(StringUtils.hasText(material.getMname())){
            jsonObj.put("mname",material.getMname());
        }
        if(StringUtils.hasText(material.getStatus())){
        	jsonObj.put("status",material.getStatus());
        }
        if(StringUtils.hasText(material.getUnit())){
            jsonObj.put("unit",material.getUnit());
        }
        if(material.getPrice()!=null){
        	jsonObj.put("price",material.getPrice());
        }
        if(material.getUpdateDate()!=null){
            jsonObj.put("updateDate",dateFormat.format(material.getUpdateDate()));
        }
        if(StringUtils.hasText(material.getUpdatePerson())){
            jsonObj.put("updatePerson",material.getUpdatePerson());
        }

        return jsonObj;
	}
	
	@InitBinder   
    public void initBinder(WebDataBinder binder) {   
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");   
        dateFormat.setLenient(true);   
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   
    }

}
